package network;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.nio.ByteBuffer;

import network.Packet.packettype;

import vmo.Chunk;
import vmo.Tile;

public class Packet_Chunk extends Packet{
	short m_instance; byte m_segment; //instance is which request this pertains to, segment is which part of the chunk this is
	Tile [][] m_tiles;
	
	public Packet_Chunk(short instance, int level, byte segment, int timestamp, Chunk chunk,InetAddress address)
	{
		m_address=address;
		m_timestamp=timestamp;
		m_instance=instance;
		m_segment=segment;
		m_type=packettype.CHUNK;		
		//build a grid of 8x8 tiles subspawned off the chunk
		int x=0, y=0;
		switch (segment)
		{
		case 1:
			x=8;
			break;
		case 2:
			x=8;
			y=8;
			break;
		case 3:
			x=0;
			y=8;
			break;
		}
		m_tiles=new Tile[8][];
		for (int i=0;i<8;i++)
		{
			m_tiles[i]=new Tile[8];
			for (int j=0;j<8;j++)
			{
				m_tiles[i][j]=chunk.m_tiles[level][i+x][j+y];
			}
		}
		
	}

	public short getInstance()
	{
		return m_instance;
	}
	
	public byte getSegment()
	{
		return m_segment;
	}
	
	public void ToChunk(Chunk chunk, int level)
	{
		int x=0, y=0;
		switch (m_segment)
		{
		case 1:
			x=8;
			break;
		case 2:
			x=8;
			y=8;
			break;
		case 3:
			x=0;
			y=8;
			break;
		}		
		
		//check if the chunk layer is null and create that layer if needbe
		if (chunk.m_tiles[level]==null)
		{
			chunk.m_tiles[level]=new Tile[16][];
			for (int i=0;i<16;i++)
			{
				chunk.m_tiles[level][i]=new Tile[16];

			}
		}
		//transcribe to the chunk
		for (int i=0;i<8;i++)
		{
			for (int j=0;j<8;j++)
			{
				chunk.m_tiles[level][i+x][j+y]=m_tiles[i][j];
			}
		}
	}
	
	public Packet_Chunk(DatagramPacket pack)
	{
		ByteBuffer buffer=ByteBuffer.wrap(pack.getData());
		Header(pack.getAddress(),buffer);
		//now, read instance
		m_instance=buffer.getShort();
		m_segment=buffer.get();
		m_tiles=new Tile[8][];
		for (int i=0;i<8;i++)
		{
			m_tiles[i]=new Tile[8];
			for (int j=0;j<8;j++)
			{
				m_tiles[i][j]=new Tile(buffer);
			}
		}
		
	}
	
	public DatagramPacket Encode(InetAddress address, int port)
	{
		byte []buffer=new byte[1024];
		ByteBuffer BB=ByteBuffer.wrap(buffer);
		//encode type
		BB.put(getTypebyte(m_type));
		BB.putInt(m_timestamp);
		BB.putShort(m_instance);
		BB.put(m_segment);
		//encode chunk data
		for (int i=0;i<8;i++)
		{
			for (int j=0;j<8;j++)
			{
				m_tiles[i][j].Encode(BB);
			
			}
		}
		
		return new DatagramPacket(buffer,buffer.length,address,port);	}
}
